package com.huyi.system.schedule;

import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

import com.alibaba.fastjson.JSON;
import com.huyi.common.util.SpringUtils;
import com.huyi.system.schedule.entity.Job;
import com.huyi.system.schedule.entity.JobLog;
import com.huyi.system.schedule.service.IJobLogService;

import lombok.extern.slf4j.Slf4j;

/**
 * 定时任务
 * 
 * @author shengli.hu
 *
 */
@Slf4j
public class ScheduleBaseJob extends QuartzJobBean {

	// 单个线程池
	private ExecutorService service = Executors.newSingleThreadExecutor();

	@Override
	protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
		long startTime = System.currentTimeMillis();
		Job job = new Job();
		JobLog jobLog = new JobLog();
		IJobLogService jobLogService = null;
		try {

			// 将任务信息解析出来
			JobDataMap dataMap = context.getMergedJobDataMap();
			Object obj = dataMap.get(ScheduleConstants.TASK_PROPERTIES);
			if (obj instanceof Job) {
				job = (Job) obj;
			} else {
				String jobJson = JSON.toJSON(obj).toString();
				job = JSON.parseObject(jobJson, Job.class);
			}

			// 获取依赖的对象
			jobLogService = (IJobLogService) SpringUtils.getBean(IJobLogService.class);
			jobLog.setJobName(job.getJobName());
			jobLog.setJobGroup(job.getJobGroup());
			jobLog.setMethodName(job.getMethodName());
			jobLog.setMethodParams(job.getMethodParams());
			jobLog.setCreateTime(new Date());

			// 执行任务
			log.info("任务开始执行 - 名称：{} 方法：{}", job.getJobName(), job.getMethodName());
			ScheduleRunnable task = new ScheduleRunnable(job.getJobName(), job.getMethodName(), job.getMethodParams());
			Future<?> future = service.submit(task);
			future.get();
			// 任务状态 0：成功 1：失败
			jobLog.setStatus(ScheduleConstants.Result.SUCCESS.getValue());
		} catch (Exception e) {
			log.error("任务执行失败 - 名称：{} 方法：{}", job.getJobName(), job.getMethodName());
			log.error("任务执行异常  - ：", e);
			// 任务状态 0：成功 1：失败
			jobLog.setStatus(ScheduleConstants.Result.FAIL.getValue());
			jobLog.setExceptionInfo(e.toString());
		} finally {
			long times = System.currentTimeMillis() - startTime;
			log.info("任务执行结束 - 名称：{} 耗时：{} 毫秒", job.getJobName(), times);
			jobLog.setJobMessage(job.getJobName() + " 总共耗时：" + times + "毫秒");
			jobLogService.addJobLog(jobLog);
		}
	}
}
